package swistak.web;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import swistak.domain.EntryCount;

@Controller
@SessionAttributes(value = {"count"})
public class SimpleClientsController {

	protected final Log logger = LogFactory.getLog(getClass());
	
	@PersistenceContext
	private EntityManager em;

	@RequestMapping(value = "/")
	public String welcome(Model model) throws Exception {
		incCountIfNeeded(model);
		return "invite";
	}
	
	@RequestMapping(value = "/{page}")
	public String invite(@PathVariable String page, Model model) throws Exception {
		incCountIfNeeded(model);
		return page;
	}
	
	public void incCountIfNeeded(Model model) throws Exception {
		if (!model.containsAttribute("count")){
			EntryCount ec = em.find(EntryCount.class, 1L);
			if (ec == null){
				ec = new EntryCount();
				ec.setCount(0L);
			}
			ec.setCount(ec.getCount() + 1);
			em.merge(ec);
			model.addAttribute("count", ec.getCount());
		}
	}
	
}
